import React, { useEffect, useState } from "react";
import Router, { withRouter } from '@/router/renderRouter';
import { deepclone, useSyncCallback } from "@/utils";
import { Table, message, Divider, Tag, Card, Modal, Select, Form, InputNumber, Input, Button, Radio, Spin, Popconfirm, Switch, Col, Row } from "antd";
import BreadcrumbBox from "@/components/Base/BreadcrumbBox";
import './index.scss'; 

import { 
  merchantWhiteListUpdate,
  merchantWhiteListDelete,
  merchantWhiteListAdd,
  merchantWhiteListPage,
} from '@/api/api'
let milCToken = {}
let first = false

const MerchantCategory = (props) => {
  const [values] = useState({
    merchantAccount: '',
    merchantName: '',
    merchantCode: '',
    whiteListIp: '',
    whitelistType: '',
  })
  const [formData, setFormData] = useState(values)
  const [modalForm] = Form.useForm();
  const [searchForm] = Form.useForm();
  const layout = { sm: 24, md: 12, lg: 12, xl: 7, xxl: 7 };
  const layoutbtn = { sm: 24, md: 24, lg: 24, xl: 4 };
  const labelCol = { sm: 24, md: 6, lg: 6, xl: 6 };
  const wrapperCol = { sm: 24, md: 18, lg: 18, xl: 18 };
  // 列表数据
  const [total, setTotal] = useState(0)
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState([]);
  
  const [id, setId] = useState(null);
  const [info, setInfo] = useState(null);
  //详情
  const [modalOpen, setModalOpen] = useState(false)
  const [modalLoading, setModalLoading] = useState(false)
  
  // 面包屑
  const breadcrumbList = ['系统设置', '白名单管理']
  // 表单头部
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      render: (text: any, row: any, index: number) => `${index + 1}`,
    },
    {
      title: '商户账号',
      dataIndex: 'merchantName',
      key: 'merchantName',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '商户编号',
      dataIndex: 'merchantCode',
      key: 'merchantCode',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '商户名称',
      dataIndex: 'merchantAccount',
      key: 'merchantAccount',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '白名单类型',
      dataIndex: 'whitelistType',
      key: 'whitelistType',
      align: 'center',
      render: (text, row, index) => (text===1?'登录':(text===2?'API':'--')),
    },
    {
      title: '白名单IP',
      dataIndex: 'whitelistIp',
      key: 'whitelistIp',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '操作时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 120,
      fixed: 'right',
      render: (text: string, record: any) => {
        return <>
          <a
            onClick={() => {
              openModel(record)
            }}
          >编辑</a>
          <Divider type="vertical" />
          <Popconfirm
              title="确定删除？"
              onConfirm={() => {
                deleteFn(record)
              }}
              okText="确定"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
        </>;
      },
    }
  ];
  // 白名单列表
  const getwhiteList = async () => {
    try {
      let {merchantAccount, merchantName, merchantCode, whiteListIp} = deepclone(formData);
      let params = {
        pageSize,
        currentPage,
        merchantAccount,
        merchantName,
        merchantCode,
        whiteListIp,
      }
      setLoading(true)
      let res = await merchantWhiteListPage(params)
      if(res.code === 0) {
        setDataSource(res.data.records || [])
        setTotal(res.data.total)
      }
      setLoading(false)
    } catch (error) {
      console.log(error)
    }
  }
  // 删除
  const deleteFn = async (data) => {
    try {
      if (typeof milCToken.source === 'function') {
        milCToken.source('终止请求'); //取消请求
      }
      let res = await merchantWhiteListDelete({
        id: data.id
      }, milCToken)
      if(res.code === 0) {
        message.success('删除成功')
        getwhiteList()
      }
    } catch (error) {
      console.log(error)
    }
  }
  
  // 搜索
  const onFinish = () => {
    setCurrentPage(1)
    setPageSize(20)
    searchData()
  }
  // 等state改变后再执行
  const searchData = useSyncCallback(() => {
    getwhiteList()
  })
  
  // 详情
  const openModel = (data=null) => {
    try {
      modalForm.resetFields();
      if(data){
        setId(data.id);
        setInfo(data)
        modalForm.setFieldsValue(info);
      }else{
        setId('');
        setInfo(null)
      }
      setModalOpen(true);
    } catch (error) {
      console.log(error)
    }
  }
  // 详情
  const saveDetail = async (data) => {
    try {
      if (typeof milCToken.source === 'function') {
        milCToken.source('终止请求'); //取消请求
      }
      setModalLoading(true)
      let res = 
      id 
      ?
      await merchantWhiteListUpdate({
        id,
        // merchantCode: data.merchantName,
        // merchantAccount: data.merchantName,
        ...data,
      }, milCToken)
      :
      await merchantWhiteListAdd({
        ...data,
        // merchantCode: data.merchantName,
        // merchantAccount: data.merchantName,
      }, milCToken)
      if(res.code === 0) {
        message.success('保存成功')
        getwhiteList()
        modalForm.resetFields();
        setModalOpen(false);
      }
      setModalLoading(false)
    } catch (error) {
      console.log(error)
    }
  }
  const handleOk = () => {
    setModalOpen(false);
  };
  const handleCancel = () => {
    setModalOpen(false);
  };
  // 更新
  useEffect(() => {
    if(first) {
      searchData()
    }
    return () => {};
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, pageSize])
  // 首次更新
  useEffect(() => {
    searchData()
    first = true
    return () => { 
      first = false
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [])
  return (
    <>
      <div className="system-component">
        <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
        <div className="system-main">
          <Form initialValues={values} form={searchForm} onFinish={(val) => {
            setFormData(val)
            onFinish()
          }}>
            <Card>
              <Row>
                <Col {...layout}>
                  <Form.Item
                    label="商户账号"
                    name="merchantAccount"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear/>
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="商户编号"
                    name="merchantCode"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear/>
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="商户名称"
                    name="merchantName"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear/>
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="ip地址"
                    name="whiteListIp"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input allowClear/>
                  </Form.Item>
                </Col>
                <Col {...layoutbtn}>
                  <div className="button-left">
                    <Button type="primary" htmlType="submit">
                      搜索
                    </Button>
                    <Button className='reset-btn' type="default" htmlType="button" onClick={() => {
                      searchForm.resetFields()
                      setFormData(searchForm.getFieldsValue(true))
                      onFinish()
                    }}>
                      重置
                    </Button>
                  </div>
                </Col>
              </Row>
            </Card>
          </Form>
          <div className="table-box">
            <Card>
              <Button type="primary" onClick={()=>{openModel()}}>
                新增白名单
              </Button>
              <Table
                loading={loading}
                size='middle'
                bordered
                scroll={{ x: 1000 }}
                rowKey={'id'}
                className='antd-table'
                dataSource={dataSource}
                pagination={false}
                pagination={{
                  size: 'default',
                  current: currentPage,
                  total,
                  showSizeChanger: true,
                  pageSize: pageSize,
                  onChange: (page, pagesize) => {
                    setCurrentPage(page)
                    setPageSize(pagesize)
                  }
                }}
                columns={columns} />
            </Card>
          </div>
        </div>
        
        <Modal title={id?'编辑白名单':'新建白名单'} visible={modalOpen} footer={null} onCancel={() => {
          setModalOpen(false)
          modalForm.resetFields()
        }}>
          <Spin spinning={modalLoading}>
            <Form
              form={modalForm}
              onFinish={(val) => {
                setInfo(val)
                saveDetail({
                  ...val
                });
              }}
            >
              <Form.Item
                labelCol={labelCol}
                wrapperCol={wrapperCol}
                label="商户账号"
                name="merchantName"
                rules={[{ required: true, message: '请输入商户账号' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                labelCol={labelCol}
                wrapperCol={wrapperCol}
                label="白名单类型"
                name="whitelistType"
                rules={[{ required: true, message: '请选择白名单类型' }]}
              >
                <Select options={[
                  {value: 1, label: '登录'},
                  {value: 2, label: 'API'},
                ]} />
              </Form.Item>
              <Form.Item
                labelCol={labelCol}
                wrapperCol={wrapperCol}
                label="备注"
                name="remark"
                rules={[{ required: true, message: '请输入备注' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                labelCol={labelCol}
                wrapperCol={wrapperCol}
                label="白名单IP"
                name="whitelistIp"
                rules={[{ required: true, message: '请输入白名单IP' }]}
              >
                <Input.TextArea />
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
                <Button className='reset-btn' type="default" htmlType="button" onClick={() => {
                  modalForm.setFieldsValue(info);
                }}>
                  重置
                </Button>
              </Form.Item>
            </Form>
          </Spin>
        </Modal>
      </div>
    </>
  )
}
export default withRouter(MerchantCategory)